package com.monkeyk.sos.infrastructure.jdbc;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.stereotype.Repository;

import com.monkeyk.sos.domain.oauth.OauthClientDetails;
import com.monkeyk.sos.domain.oauth.OauthRepository;
import com.monkeyk.sos.domain.shared.GuidGenerator;
import com.monkeyk.sos.util.WebUtils;

@Repository("oauthRepositoryJdbc")
public class OauthRepositoryJdbc implements OauthRepository {



    private static OauthClientDetailsRowMapper oauthClientDetailsRowMapper = new OauthClientDetailsRowMapper();


    @Autowired
    private JdbcTemplate jdbcTemplate;


    @Override
    public OauthClientDetails findOauthClientDetails(String clientId) {
        final String sql = " select * from oauth_client_details where  client_id = ? ";
        final List<OauthClientDetails> list = this.jdbcTemplate.query(sql, new Object[]{clientId}, oauthClientDetailsRowMapper);
        return list.isEmpty() ? null : list.get(0);
    }

    @Override
    public List<OauthClientDetails> findAllOauthClientDetails() {
        final String sql = " select * from oauth_client_details order by create_time desc ";
        return this.jdbcTemplate.query(sql, oauthClientDetailsRowMapper);
    }

    @Override
    public void updateOauthClientDetailsArchive(String clientId, boolean archive) {
        final String sql = " update oauth_client_details set archived = ? where client_id = ? ";
        this.jdbcTemplate.update(sql, archive, clientId);
    }

    @Override
    public void saveOauthClientDetails(final OauthClientDetails clientDetails) {
        final String sql = " insert into oauth_client_details(client_id,resource_ids,client_secret,scope,authorized_grant_types,web_server_redirect_uri," +
                " authorities,access_token_validity,refresh_token_validity,additional_information,trusted,autoapprove) values (?,?,?,?,?,?,?,?,?,?,?,?)";

        this.jdbcTemplate.update(sql, new PreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps) throws SQLException {
                ps.setString(1, clientDetails.clientId());
                ps.setString(2, clientDetails.resourceIds());
                ps.setString(3, clientDetails.clientSecret());
                ps.setString(4, clientDetails.scope());
                ps.setString(5, clientDetails.authorizedGrantTypes());
                ps.setString(6, clientDetails.webServerRedirectUri());
                ps.setString(7, clientDetails.authorities());
                ps.setObject(8, clientDetails.accessTokenValidity());
                ps.setObject(9, clientDetails.refreshTokenValidity());
                ps.setString(10, clientDetails.additionalInformation());
                ps.setBoolean(11, clientDetails.trusted());
                ps.setString(12, clientDetails.autoApprove());

            }
        });
    }
	/*
	 * 查询clientId数目
	 */
	private Integer findOauthClientNum(String clientId) {
		final String sql = " select count(0) from oauth_client_details where  client_id = '"+clientId+"'";
		return jdbcTemplate.queryForObject(sql,Integer.class);
	}

	@Override
	public Map<String, String> createClientIdAndSecret() {
		Map<String,String> map = new HashMap<String, String>();
		String clientId = WebUtils.getRandomString();
	    if(findOauthClientNum(clientId)>0){
	    	clientId= WebUtils.getRandomString();
	    };
	    String clientSecret = GuidGenerator.generate();
	    map.put("clientId", clientId);
	    map.put("clientSecret", clientSecret);
		return map;
	}
}
